package cn.loioi.distribution.spring;

import javax.sql.DataSource;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.transaction.PlatformTransactionManager;

import cn.loioi.distribution.DistributionManage;
import cn.loioi.distribution.spring.db.SpringDbManger;

public class SpringDistributionFactoryBeen implements FactoryBean<DistributionManage>, InitializingBean {
	private DataSource dataSource;
	private PlatformTransactionManager transactionManager;

	private SpringDbManger dbManger;
	private DistributionManage distributionManage;

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public PlatformTransactionManager getTransactionManager() {
		return transactionManager;
	}

	public void setTransactionManager(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public Class<?> getObjectType() {
		return DistributionManage.class;
	}

	@Override
	public DistributionManage getObject() throws Exception {
		if (distributionManage == null) this.afterPropertiesSet();

		return distributionManage;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// 初始化数据库工具
		if (dbManger == null) {
			if (dataSource == null) throw new IllegalArgumentException("dataSource is null");
			if (transactionManager == null) throw new IllegalArgumentException("transactionManager is null");

			dbManger = new SpringDbManger();
			dbManger.setDataSource(dataSource);
			dbManger.setTransactionManager(transactionManager);

			dbManger.createTable();
		}

		if (distributionManage == null) {
			distributionManage = new DistributionManage();
			distributionManage.setDbManger(dbManger);
			distributionManage.afterPropertiesSet();
		}
	}
}
